//
//  HDRecognizeeVC.swift
//  HuaDaoPeifu
//
//  Created by ZERO on 2018/6/7.
//  Copyright © 2018年 paiyipai. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 如何是选择被保人页面，只需要设置 selectRecognizeeCompletionHandler ，即可实现选择被保人，并跳转的功能
class HDRecognizeeVC: UIViewController , UITableViewDelegate, UITableViewDataSource{

    fileprivate var list = [HDRecognizeeModel]()
    fileprivate var canSelected : Bool = false // 1显示可选择按钮
    
    
    var selectRecognizeeCompletionHandler:((_ recognizee:HDRecognizeeModel)->())?{
        didSet{
            if selectRecognizeeCompletionHandler != nil {
                canSelected = true
                title = "选择被保人"
            }
        }
    }
    /// 已选中的cell
    fileprivate var selectedCell : UITableViewCell?
    
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUI()
        loadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        loadData()
    }
    
    func setUI() {
        tableView.register(UINib(nibName: "HDRecognizeeCell", bundle: nil), forCellReuseIdentifier: "HDRecognizeeCell")
        tableView.allowsSelection = canSelected
        tableView.rowHeight = 60
    }
    
    func loadData() {
        
        HDApiManagerHandler.requestRecognizeeList { (list:[HDRecognizeeModel]?) in
            if let list = list {
                self.list = list
            }else {
                self.list = []
            }
            self.tableView.reloadData()
        }
    }
    
    /// 删除被保人功能
    func deleteRecognizee(_ indexPath:IndexPath) {
        let model = list[indexPath.row]
        
        HDApiManagerHandler.deleteRecognizee(model.id) {[unowned self] (result:HDApiResult?) in
            guard let result = result else {
                SVProgressHUD.showError("网络开小差了，请一会再试...")
                return // 请求异常
            }

            if result.status == .Success {
                // 删除成功
                self.list.remove(at: indexPath.row)
                self.tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.left)
                SVProgressHUD.showSuccess("删除成功！")
            }
        }
    }
    /// 跳转编辑被保人界面
    func editRecognizee(_ indexPath:IndexPath) {
        let model = list[indexPath.row]
        let sb = UIStoryboard(name: "HDRecognizeeEditVC", bundle: nil)
        let vc = sb.instantiateInitialViewController() as! HDRecognizeeEditVC
        vc.editRecognizee = model
        vc.mode = .Modify
        navigationController?.pushViewController(vc, animated: true)
    }
    
    /// 新增被保人
    @IBAction func addAction(_ sender: UIButton) {
//        navigationController?.pushViewController(HDRecognizeeOtherVC(), animated: true)
        
        let sb = UIStoryboard(name: "HDRecognizeeEditVC", bundle: nil)
        let vc = sb.instantiateInitialViewController()
        
        navigationController?.pushViewController(vc!, animated: true)
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.list.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "HDRecognizeeCell", for: indexPath) as! HDRecognizeeCell
        cell.canSelected = canSelected
        cell.delegate = self
        let recognizee = self.list[indexPath.row]
        cell.recognizee = recognizee
        return cell
    }
    
    
//    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
//        return true
//    }
//
//    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
//        let actionDelete = UITableViewRowAction(style: .default, title: "删除") {[unowned self] (action, indexPath) in
//            let ac = UIAlertController(title: "删除被保人", message: "是否确定要删除被保人？", preferredStyle: .actionSheet)
//
//            let action1 = UIAlertAction(title: "确定", style: .destructive, handler: { (action) in
//                self.deleteRecognizee(indexPath)
//            })
//            ac.addAction(action1)
//
//            let action2 = UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
//            })
//            ac.addAction(action2)
//
//            self.present(ac, animated: true, completion: nil)
//        }
//        let actionModify = UITableViewRowAction(style: .normal, title: "修改") { (action, indexPath) in
//            self.editRecognizee(indexPath)
//        }
//        return [actionDelete,actionModify]
//    }
//
//    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        tableView.deselectRow(at: indexPath, animated: true)
//        let cell = tableView.cellForRow(at: indexPath) as! HDRecognizeeNewCell
//        cell.accessoryType = .checkmark
//        let model = cell.recognizee
//        if let model = model,let selectRecognizeeCompletionHandler = selectRecognizeeCompletionHandler {
//            selectRecognizeeCompletionHandler(model)
//            self.navigationController?.popViewController(animated: true)
//        }
//        if let selectedCell = selectedCell {
//            selectedCell.accessoryType = .none
//        }
//        selectedCell = cell
//    }
}

extension HDRecognizeeVC: HDRecognizeeCellDelegate {
    func recognizeeCellWillSelect(cell: HDRecognizeeCell) {
        
        let model = cell.recognizee
        if let model = model,
        let selectRecognizeeCompletionHandler = selectRecognizeeCompletionHandler {
            
            selectRecognizeeCompletionHandler(model)
            self.navigationController?.popViewController(animated: true)
        }

        selectedCell = cell
    }
    
    func recognizeeCellWillDelete(cell: HDRecognizeeCell) {
        
        if let indexPath = tableView.indexPath(for: cell) {
            let ac = UIAlertController(title: "删除被保人", message: "是否确定要删除被保人？", preferredStyle: .actionSheet)

            let action1 = UIAlertAction(title: "确定", style: .destructive, handler: { (action) in
                self.deleteRecognizee(indexPath)
            })
            ac.addAction(action1)

            let action2 = UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
            })
            ac.addAction(action2)

            self.present(ac, animated: true, completion: nil)
            
        }
    }
    
    func recognizeeCellWillModify(cell: HDRecognizeeCell) {
        if let indexPath = tableView.indexPath(for: cell) {
            self.editRecognizee(indexPath)
        }
    }
}


